<template>
  <div class="login" id="login-app">
    <div class="login-box">
      <img src="../assets/login/login-l.png" alt="" />
      <div class="login-form">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
          <div class="login-form-title">
            <img src="../assets/login/logo.png" style="width:139px;height:42px;" alt="" />
          </div>
          <el-form-item prop="email">
            <el-input v-model="loginForm.email" type="text" auto-complete="off" placeholder="账号" maxlength="20"
              prefix-icon="iconfont icon-user" />
          </el-form-item>
          <el-form-item prop="passwordHash">
            <div class="password-container">
              <el-input v-model="loginForm.passwordHash" :type="showPassword ? 'text' : 'password'" placeholder="密码"
                prefix-icon="iconfont icon-lock" maxlength="20" @keyup.enter.native="handleLogin" />
              <span class="el-icon-view" @click="togglePassword"></span>
              <span class="register-link" @click="navigateToRegister">点击注册</span>
              <span class="passwordr-link" @click="navigateToResetPassword">找回密码</span>
            </div>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button :loading="loading" class="login-btn" size="medium" type="primary" style="width:100%;"
              @click.native.prevent="login">
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
          <!-- 新增微信登录按钮 -->
          <el-form-item style="width:100%; text-align:center;">
            <el-button class="wechat-login-btn" size="medium" type="success" @click.native.prevent="openWeChatDialog">
              <i class="iconfont icon-wechat" style="font-size: 20px;"></i> 使用微信登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 微信二维码弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="微信登录" width="400px">
      <div v-if="qrcodeUrl">
        <img :src="qrcodeUrl" alt="微信登录二维码" style="width: 100%; height: 100%;" />
      </div>
    </el-dialog>

    <!-- 绑定邮箱的弹窗 -->
    <el-dialog :visible.sync="bindingDialogVisible" title="绑定邮箱" width="400px">
      <el-form ref="bindingForm" :model="bindingForm" :rules="bindingRules">
        <el-form-item prop="email">
          <el-input v-model="bindingForm.email" type="text" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="passwordHash">
          <el-input v-model="bindingForm.passwordHash" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="bindEmailPassword">绑定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { loginApi, bindEmailApi, checkOpenIdApi } from '@/api/login';
export default {
  data() {
    return {
      loginForm: {
        email: '',
        passwordHash: '',
      },
      bindingForm: {
        email: '',
        passwordHash: '',
        openid: '',
        nickname: '',
        headimgurl: '',
      },
      bindingDialogVisible: false,
      loading: false,
      showPassword: false,
      qrcodeUrl: '',
      dialogVisible: false,
      ws: null,
    };
  },
  computed: {
    loginRules() {
      const validateEmail = (rule, value, callback) => {
        // 邮箱正则表达式，用于基本的邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        // 检查输入是否为空
        if (!value || value.length < 1) {
            callback(new Error('请输入邮箱地址'));
        } else if (!emailRegex.test(value)) {
            // 检查邮箱格式是否正确
            callback(new Error('请输入有效的邮箱地址'));
        } else {
            callback(); // 验证成功
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码必须在6位以上'));
        } else {
          callback();
        }
      };
      return {
        email: [{ validator: validateEmail, trigger: 'blur' }],
        passwordHash: [{ validator: validatePassword, trigger: 'blur' }]
      };
    },
    bindingRules() {
      const validateEmail = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入邮箱'));
        } else {
          callback();
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码必须在6位以上'));
        } else {
          callback();
        }
      };
      return {
        email: [{ validator: validateEmail, trigger: 'blur' }],
        passwordHash: [{ validator: validatePassword, trigger: 'blur' }],
      };
    },
  },
  methods: {
    togglePassword() {
      this.showPassword = !this.showPassword; // 切换密码显示状态
    },
    navigateToRegister() {
      // 跳转到注册页面
      window.location.href = '/register'; // 根据实际注册页面的 URL 进行更新
    },
    navigateToResetPassword() {
      // 跳转到找回密码页面
      window.location.href = '/reset-password'; // 根据实际找回密码页面的 URL 进行更新
    },
    async login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await loginApi({
      email: this.loginForm.email,
      passwordHash: this.loginForm.passwordHash, // 应在前端处理密码加密
    });
          try {
            const response = await loginApi({
      email: this.loginForm.email,
      passwordHash: this.loginForm.passwordHash, // 应在前端处理密码加密
    });
            if (response && response.code === 200) { // 根据实际接口返回的成功代码进行判断
              // 登录成功，进行相应操作
              this.$message.success('登录成功');
              // 例如，保存用户信息，跳转页面等
              localStorage.setItem('token', response.data); // 直接存储 token 字符串
              this.$router.push('/main'); // 假设登录成功后跳转到主页
            } else {
              this.$message.error(response.msg || '登录失败');
            }
          } catch (error) {
            this.$message.error('登录过程中发生错误');
          } finally {
            this.loading = false;
          }
        }
      });
    },
    async bindEmailPassword() {
      this.$refs.bindingForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await bindEmailApi({
              email: this.bindingForm.email,
              passwordHash: this.bindingForm.passwordHash,
              openid: this.bindingForm.openid,
              nickname: this.bindingForm.nickname,
              headimgurl: this.bindingForm.headimgurl,
            });
            if (response && response.code === 200) {
              this.$message.success('绑定成功');
              this.bindingDialogVisible = false;
              this.$router.push('/main');
            } else {
              this.$message.error(response.msg || '绑定失败');
            }
          } catch (error) {
            this.$message.error('绑定过程中发生错误');
          }
        }
      });
    },
    async openWeChatDialog() {
      try {
        this.qrcodeUrl = 'http://localhost:8080/oauth/weixin/login';
        this.dialogVisible = true;
        this.connectWebSocket();
      } catch (error) {
        this.$message.error('获取微信登录二维码失败');
      }
    },
    async connectWebSocket() {
      this.socket = new WebSocket('ws://localhost:8080/ws');

      this.socket.onopen = () => {
        console.log('WebSocket连接成功');
      };

      this.socket.onmessage = async (event) => {
        const message = JSON.parse(event.data);
        if (message.openid != null) {
          this.bindingForm.openid = message.openid;
          this.bindingForm.nickname = message.nickname;
          this.bindingForm.headimgurl = message.headimgurl;

          try {
            // 检查 openid 是否存在于数据库中
            const checkResponse = await checkOpenIdApi({ openid: message.openid });

            // 根据后端返回的结果处理逻辑
            if (checkResponse.code===200) {
              // 如果 openid 存在
              localStorage.setItem('userInfo', JSON.stringify(checkResponse.data));
              this.$router.push('/main');
              this.$message.success('微信登录成功');
            } else {
              // 如果 openid 不存在
              this.dialogVisible = false;
              this.bindingDialogVisible = true;
            }
          } catch (error) {
            this.$message.error('查询 openid 过程中发生错误');
          }
        }
      };

      this.socket.onclose = () => {
        console.log('WebSocket connection closed');
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        this.$message.error('WebSocket 连接出现错误');
      };
    }
  },
  mounted() {
    this.connectWebSocket();
  }
};
</script>

<style scoped>
.wechat-login-btn {
  background-color: #00c300;
  color: white;
  border-radius: 17px;
  padding: 11px 20px;
  font-weight: 500;
  font-size: 14px;
  border: 0;
  margin-top: 10px;
}

.wechat-login-btn:hover,
.wechat-login-btn:focus {
  background-color: #00a600;
  color: white;
}

.icon-wechat {
  margin-right: 8px;
}

/* Dialog 样式调整 */
.el-dialog {
  max-width: 200px;
}

.el-dialog__header {
  text-align: center;
}

.el-dialog__body {
  display: flex;
  justify-content: center;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 97.7vh;
  /* 使背景占满整个视口高度 */
  width: 99.2vw;
  /* 使背景占满整个视口宽度 */
  background-color: #e0e6f8;
}

.login-box {
  width: 70%;
  height: 70%;
  border-radius: 8px;
  display: flex;
}

.login-box img {
  width: 60%;
  height: auto;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  background: #ffffff;
  width: 40%;
  border-radius: 0px 8px 8px 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form .el-form {
  width: 214px;
  height: 307px;
}

.login-form .el-form-item {
  margin-bottom: 30px;
}

.login-form .el-form-item.is-error .el-input__inner {
  border: 0 !important;
  border-bottom: 1px solid #fd7065 !important;
  background: #fff !important;
}

.login-form .input-icon {
  height: 32px;
  width: 18px;
  margin-left: -2px;
}

.login-form .el-input__inner {
  border: 0;
  border-bottom: 1px solid #e9e9e8;
  border-radius: 0;
  font-size: 14px;
  font-weight: 400;
  color: #333333;
  height: 32px;
  line-height: 32px;
}

.login-form .el-input__prefix {
  left: 0;
}

.login-form .el-input--prefix .el-input__inner {
  padding-left: 26px;
}

.login-form .el-input__inner::placeholder {
  color: #aeb5c4;
}

.login-form .el-form-item--medium .el-form-item__content {
  line-height: 32px;
}

.login-form .el-input--medium .el-input__icon {
  line-height: 32px;
}

.login-btn {
  border-radius: 17px;
  padding: 11px 20px !important;
  margin-top: 10px;
  font-weight: 500;
  font-size: 14px;
  border: 0;
  background-color: #0b8bed;
}

.login-btn:hover,
.login-btn:focus {
  /* background: #FFC200; */
  /* color: #ffffff; */
}

.login-form-title {
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
}

.login-form-title .title-label {
  font-weight: 500;
  font-size: 20px;
  color: #333333;
  margin-left: 10px;
}

.password-container {
  position: relative;
}

.register-link {
  position: absolute;
  bottom: -30px;
  /* Adjust as needed */
  right: 0;
  font-size: 12px;
  color: #3794f7;
  cursor: pointer;
}

.el-icon-view {
  position: absolute;
  bottom: 13px;
  /* Adjust as needed */
  right: 5px;
  font-size: 12px;
  color: #242628;
  cursor: pointer;
}

.passwordr-link {
  position: absolute;
  bottom: -30px;
  /* Adjust as needed */
  left: 110px;
  font-size: 12px;
  color: #3794f7;
  cursor: pointer;
}

.register-link:hover {
  text-decoration: underline;
}

.passwordr-link:hover {
  text-decoration: underline;
}
</style>
